package com.kavian.eastmoney;

import java.util.ArrayList;
import java.util.List;

import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;

import com.kavian.common.util.HttpClientUtil;

/**
 * @author Annie
 * 
 */
public class Text {

	private static final String URL = "http://data.eastmoney.com";
	private static final String CHARSET = "gb2312";

	public static void main(String[] args) throws Exception {
		String url = "http://data.eastmoney.com/Stock/lhb/600792.html";
		
		String content = HttpClientUtil.httpGet(url, CHARSET);
		
		Parser parser = Parser.createParser(content, CHARSET);
		NodeFilter tabFilter = new AndFilter(new NodeClassFilter(TableTag.class),
				new HasAttributeFilter("class", "tab2"));
		NodeList tabList = parser.extractAllNodesThatMatch(tabFilter);
		
		//for (int i = 0; i < tabList.size(); i++) {
			TableTag tableTag = (TableTag)tabList.elementAt(0);
			
			TableRow[] tr = tableTag.getRows();
			for (int j = 0; j < tr.length; j++) {
				System.out.println(tr[j].toHtml());
			}
		//}
		
	}
	
	/**
	 * 1. 获取所需要的url
	 * @return
	 * @throws Exception
	 */
	public List<String> searchLink()  throws Exception{
		List<String> links = new ArrayList<String>();
		String content = HttpClientUtil.httpGet(URL+"/stock/lhb.html", CHARSET);

		Parser parser = Parser.createParser(content, CHARSET);
		NodeFilter divFilter = new AndFilter(new NodeClassFilter(Div.class),
				new HasAttributeFilter("class", "content1"));
		NodeList divList = parser.extractAllNodesThatMatch(divFilter);

		String divContent = divList.elementAt(0).toHtml();

		Parser divParser = Parser.createParser(divContent, CHARSET);
		NodeFilter linkFilter = new NodeClassFilter(LinkTag.class);
		NodeList linkList = divParser.extractAllNodesThatMatch(linkFilter);
		
		for (int i = 0; i < linkList.size(); i++) {
			String linkContent = linkList.elementAt(i).toHtml();
			
			if(linkContent.indexOf("class=") == -1 && linkContent.indexOf("title=") != -1 ){
				
				LinkTag link = (LinkTag) linkList.elementAt(i);
				String href = link.getAttribute("href");
				links.add(URL+href);
			};
		}
		return links;
	}
}